import json
from statistics import mean

def calculate_polygon_centroid(coordinates):
    """
    计算多边形的中心点
    :param coordinates: 多边形坐标列表
    :return: 中心点坐标 [x, y]
    """
    # 对于MultiPolygon，取第一个面的第一个环
    if len(coordinates[0][0]) > 0:
        coords = coordinates[0][0]  # 获取外环坐标
    else:
        coords = coordinates[0]  # 简单多边形的情况
    
    # 计算所有顶点的平均值作为中心点
    x_coords = [point[0] for point in coords]
    y_coords = [point[1] for point in coords]
    
    return [mean(x_coords), mean(y_coords)]

def convert_fill_to_point(input_geojson):
    """
    将面数据转换为点数据
    :param input_geojson: 输入的GeoJSON数据
    :return: 转换后的点数据GeoJSON
    """
    output_geojson = {
        "type": "FeatureCollection",
        "features": []
    }
    
    for feature in input_geojson["features"]:
        if feature["geometry"]["type"] in ["Polygon", "MultiPolygon"]:
            # 计算中心点
            centroid = calculate_polygon_centroid(feature["geometry"]["coordinates"])
            
            # 创建新的点要素
            point_feature = {
                "type": "Feature",
                "geometry": {
                    "type": "Point",
                    "coordinates": centroid
                },
                "properties": feature.get("properties", {})  # 保留原有的properties
            }
            
            output_geojson["features"].append(point_feature)
    
    return output_geojson

def main():
    # 读取输入文件
    input_file = "d:/xunJi/python/my/tools/geojson/L2_fill.json"
    output_file = "d:/xunJi/python/my/tools/geojson/L2_point.json"
    
    try:
        with open(input_file, 'r', encoding='utf-8') as f:
            input_geojson = json.load(f)
        
        # 转换数据
        output_geojson = convert_fill_to_point(input_geojson)
        
        # 保存转换后的数据
        with open(output_file, 'w', encoding='utf-8') as f:
            json.dump(output_geojson, f, ensure_ascii=False, indent=2)
        
        print(f"转换完成！输出文件已保存至: {output_file}")
        
    except Exception as e:
        print(f"处理过程中出现错误: {str(e)}")

if __name__ == "__main__":
    main()